package com.motu.monstercity.server.game.timedtask;

import com.motu.monstercity.server.game.commondata.feast.FeastMain;
import com.motu.monstercity.server.game.commondata.world.WorldConstant;
import com.motu.monstercity.server.game.logic.FeastManager;
import com.motu.monstercity.server.game.logic.GameUser;
import com.motu.monstercity.server.game.logic.WorldBossManager;
import com.motu.monstercity.server.game.logic.WorldManager;
import com.motu.monstercity.server.game.userdata.*;
import com.motu.vertx.module.utility.threadpool.DBLogManager;
import com.motu.vertx.module.utility.toolset.ErrorWord;
import com.motu.vertx.module.utility.toolset.TimeUtils;
import com.motu.vertx.module.utility.toolset.Tool;
import io.vertx.core.json.JsonObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

public class WorldBossTask implements Runnable, Delayed {
	public final static Logger logger = LoggerFactory.getLogger(WorldBossTask.class);

	private long userId;// 行军的人
	private int teamId;
	private String uniqueId; // 任务唯一id
	private long execTime;// 结束时间,任务的执行时间 举办时间+时长
	private JsonObject jsonObject;


	public long getUserId() {
		return userId;
	}

	public int getTeamId() {
		return teamId;
	}

	public String getUniqueId() {
		return uniqueId;
	}

	private long getExecTime() {
		return this.execTime;
	}
	private JsonObject getJsonObject() {
		return this.jsonObject;
	}


	public WorldBossTask(JsonObject obj) {
		this.userId = obj.getLong("user_id");
		this.execTime = obj.getLong("end_time");
		this.uniqueId = obj.getString("unique_id");
		this.teamId = obj.getInteger("team_id");
		this.jsonObject = obj;
	}

	@Override
	public void run() {
		TimedTaskManager.sendWorkTaskRetry(TimeTaskCmd.WORK_WORLD_BOSS_BATTLE, getJsonObject());// 发送失败进行重发
	}

	@Override
	public long getDelay(TimeUnit unit) {
		return unit.convert(getExecTime() - TimeUtils.getCurTime(), TimeUnit.SECONDS);
	}

	@Override
	public int compareTo(Delayed o) {
		WorldBossTask that = (WorldBossTask) o;
		return getExecTime() > that.execTime ? 1 : (getExecTime() < that.execTime ? -1 : 0);
	}

	/**
	 *  处理派对结束的逻辑
	 * @param task
	 */
	public static void runTask(JsonObject task){
		try {
			logger.info("### WorldBossTask runTask = " + task);
			long userId = task.getLong("user_id");
			int teamId = task.getInteger("team_id");
			String uniqueId = task.getString("unique_id");
			// 判断时间是否过期，过期不完成事件, 如果status和uniqueId不是期望则拦截执行
			WorldBossManager.autoArrive(userId,teamId,uniqueId);
		} catch (Exception e){
			String errMsg = Tool.getException(e);
			logger.error("###WorldBossTask error:" + errMsg);
			DBLogManager.addServerCrashLog(999999, errMsg);
		}
	}
}
